import { SecondHeaderC, TableC } from '@/comps/index';
import PropTypes from 'prop-types';
import React, { useEffect, useState, useMemo, useCallback, forwardRef, useImperativeHandle } from 'react';
import { connect } from 'dva';
import { cloneDeep } from 'lodash';
import styles from './index.less';

const TitleTable = forwardRef((props, ref) => {
  const { sorterKeys = [], title = null, payloadType, effect, columns, setRowClass = () => {}, onClickRow = () => {}, dispatch, dateRange, isPagination = true } = props;
  const [total, setTotal] = useState(0);
  const [tableLoading, setTableLoading] = useState(false);
  const [dataSource, setDataSource] = useState([]);
  const [pageInfo, setPageInfo] = useState({
    currentPage: 1,
    numInPage: 10,
  });
  const [sortedInfo, setSortedInfo] = useState({});
  // 需要暴露的实例
  useImperativeHandle(ref, () => ({
    // 手动初始化排序和分页
    reset: () => {
      setSortedInfo({});
      setPageInfo({
        currentPage: 1,
        numInPage: 10,
      });
    },
    // 获取dataSource
    getDataSource: () => dataSource,
  }));
  const initData = () => {
    setTableLoading(true);
    const pageObj = isPagination ? pageInfo : {};
    const payloadTypeObj = title ? payloadType : {};
    dispatch({
      type: effect,
      payload: {
        // ...pageObj,
        ...dateRange,
        ...payloadTypeObj,
        ...sortedInfo,
      },
      callback: (data) => {
        setDataSource(data.dataSource);
        setTotal(data?.pageInfo?.total || data.dataSource.length);
        setTableLoading(false);
      },
    });
  };
  useEffect(() => {
    const condition = title ? payloadType.productType && dateRange.startDate && dateRange.endDate : dateRange.startDate && dateRange.endDate;
    if (condition) initData();
  }, [dateRange.startDate, dateRange.endDate, sortedInfo]);
  const changeTable = useCallback((pagination, filters, sorter, extra) => {
    if (extra.action === 'paginate') {
      setPageInfo({
        ...pageInfo,
        numInPage: pagination?.pageSize ?? 10,
        currentPage: pagination?.current ?? 1,
      });
    }
    if (extra.action === 'sort') {
      setSortedInfo({
        sortType: sorter.order,
        sortItem: sorter.order ? sorter.columnKey : undefined,
      });
    }
  }, []);
  const enhanceColumns = useMemo(() => {
    const columnDeep = cloneDeep(columns);
    columnDeep.map((item) => {
      if (sorterKeys.includes(item.key)) {
        item.sorter = true;
        item.sortOrder = sortedInfo?.sortItem === item.key ? sortedInfo?.sortType : undefined;
      }
    });
    return columnDeep;
  }, [sortedInfo, columns]);
  return (
    <div style={{ marginBottom: 10 }} className={styles.titleTable}>
      {title ? <SecondHeaderC title={title} /> : null}
      <TableC
        rowClassName={(record) => {
          return setRowClass ? setRowClass(record) : '';
        }}
        onRow={(record) => {
          return {
            onClick: () => {
              onClickRow && onClickRow(record);
            },
          };
        }}
        selfScrollY={true}
        rowKey={(record) => record?.id}
        scroll={{ x: 'max-content', y: 300 }}
        columns={enhanceColumns}
        dataSource={dataSource[0] === null ? [] : dataSource}
        current={pageInfo.currentPage}
        total={total}
        pageSize={pageInfo.numInPage}
        onChange={changeTable}
        hidePage={total < 10}
        loading={tableLoading}
      />
    </div>
  );
});
TitleTable.propsTypes = {
  title: PropTypes.element.isRequired, // 标题
  payloadType: PropTypes.object.isRequired, // 查询参数
  onClickRow: PropTypes.func, // 点击行
  setRowClass: PropTypes.func, // 设置行的高亮类目
  columns: PropTypes.array.isRequired,
  effect: PropTypes.string.isRequired, // dispatch type
  dateRange: PropTypes.object.isRequired, // 时间区间
  sorterKeys: PropTypes.array, // 需要排序的keys
  isPagination: PropTypes.bool, // 是否分页
};
const mapState = ({ loading, globalM }) => ({ loading, globalM });
export default connect(mapState, null, null, { forwardRef: true })(TitleTable);
